package com.lepu.app.fun.tool.cjsj;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.ArrayWheelAdapter;
import com.core.lib.ui.wheel.NumericWheelAdapter;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.DateType;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.cjsj.bean.BeanToolChanJian;
import com.lepu.app.fun.tool.ymsjb.remind.Alarm;
import com.lepu.app.fun.tool.ymsjb.remind.AlarmTipsManager;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class ChanJianAddActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,AsyncRequest {
	private String REQUEST_DATA = "request_data";
	private String REQUEST_DATA_UPDATE = "request_data_update";
	
	private TextView mDateEdit;
	private TextView mRemindEdit;
	private EditText mNoteEdit;
	private TextView mCountTextView;
	private BeanToolChanJian mBean = null;
	
	private int mMaxLength = 200;
	public String [] mDateArray = null;
	public int mCurrentItem = 1;
	public String mTime = "";
	
	private TextView mYesTextView;
	private TextView mNoTextView;
	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tool_chanjian_add_activity);

		UtilityBase.setStatusBarRes(this, R.color.color_bmi, true);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("添加产检时间");
		topbar.setTopbarBackground(R.color.color_bmi);
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mDateArray = getResources().getStringArray(R.array.array_cjsj_date);
		mBean = (BeanToolChanJian) getIntent().getSerializableExtra("chanjian");
		
		mDateEdit = (TextView) findViewById(R.id.dateEditText);
		mRemindEdit = (TextView) findViewById(R.id.remindEditText);
		mNoteEdit = (EditText) findViewById(R.id.noteEditText);
		mCountTextView = (TextView) findViewById(R.id.noteCountTextView);
		mYesTextView = (TextView) findViewById(R.id.yesText);
		mNoTextView = (TextView) findViewById(R.id.noText);
		
		mYesTextView.setSelected(true);
		
		mDateEdit.setOnClickListener(onClick);
		mRemindEdit.setOnClickListener(onClick);
		mYesTextView.setOnClickListener(onClick);
		mNoTextView.setOnClickListener(onClick);
		
		mNoteEdit.addTextChangedListener(mTextWatcher);
		
		if(mBean != null){
			mDateEdit.setText(mBean.date);
			mRemindEdit.setText(mDateArray[mBean.remindIndex]+" "+mBean.remindTime);
			mNoteEdit.setText(mBean.note);
			
			mTime = mBean.remindTime;
			mCurrentItem = mBean.remindIndex;
			mCountTextView.setText(String.format("(%d/%d)", mNoteEdit.getText().toString().length(), mMaxLength));
			
			if(mBean.remindIs == 0){
				mNoTextView.setSelected(true);
				mYesTextView.setSelected(false);
				
				mRemindEdit.setClickable(false);
				mRemindEdit.setText("");
				mTime="";
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black3));
			}else if(mBean.remindIs == 1){
				mNoTextView.setSelected(false);
				mYesTextView.setSelected(true);
				
				mRemindEdit.setClickable(true);
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black));
			}
		}
		
	}

	@SuppressLint("DefaultLocale")
	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.testButton:
			String date = mDateEdit.getText().toString().trim();
			String remindDate = mRemindEdit.getText().toString().trim();
			String note = mNoteEdit.getText().toString().trim();

			if (TextUtils.isEmpty(date)) {
				UIHelper.showToast(this, "请选择检查时间");
				return;
			}
			
			if (TextUtils.isEmpty(remindDate)&&mYesTextView.isSelected()) {
				UIHelper.showToast(this, "请选择提醒时间");
				return;
			}
			
			if(TextUtils.isEmpty(note)){
				note="";
			}
//			
			if(note.length()>200){
				UIHelper.showToast(this, "请填写200字以内备注");
				return;
			}
			
			int remind = 0;
			if(mYesTextView.isSelected()){
				remind =1;
			}
			
			if(mNoTextView.isSelected()){
				remind =0;
			}
			
			//-----remind------
			if(remind == 0){
				
			}else if(remind == 1){
				//修改的话删除之前提醒
				if(mBean != null){
					if(mBean.remindIs == 1){
						long alarmTime = DateUtil.getLongTimeAll(mBean.date +" "+mBean.remindTime);
						if(mBean.remindIndex == 0){  //当天
							
						}else if(mBean.remindIndex == 1){  //前一天
							alarmTime = alarmTime - DateUtil.DAY_MILLIS;
						}else if(mBean.remindIndex == 2){  //前三天
							alarmTime = alarmTime - (DateUtil.DAY_MILLIS * 3);
						}
						
						String timeStr = String.valueOf(alarmTime);
					    int alarmId = Integer.valueOf(timeStr.substring(timeStr.length() - 8, timeStr.length()));
					    
					    //删除提醒
	                	Alarm.closeRemind(MyApplication.alarmManager, this, alarmId);
	                    AlarmTipsManager.deleteItem(alarmId); 
					}
				}
				
				//设置闹钟
				Alarm alarm = new Alarm();
				
				long alarmTime = DateUtil.getLongTimeAll(date +" "+mTime);
				if(mCurrentItem == 0){  //当天
					
				}else if(mCurrentItem == 1){  //前一天
					alarmTime = alarmTime - DateUtil.DAY_MILLIS;
				}else if(mCurrentItem == 2){  //前三天
					alarmTime = alarmTime - (DateUtil.DAY_MILLIS * 3);
				}
				
				alarm.uid = LoginUtil.getUserId();
				alarm.alarmTime = alarmTime;
				alarm.showTime = remindDate;
				alarm.setTime = alarmTime;
				alarm.note = "您的产检时间临近了，记得按时前往医院检查哦";
				Alarm.setRemind(alarm, MyApplication.alarmManager, ChanJianAddActivity.this);
			
			}
		    
			//bean
			BeanToolChanJian bean = new BeanToolChanJian();
			bean.uid = LoginUtil.getUserId();
			bean.date = date;
			bean.remindIndex = mCurrentItem;
			bean.remindTime = mTime;
			bean.remindIs = remind;
			bean.note = note;
			
			if(mBean == null){
				//BeanToolChanJian.insert(bean);
				request(bean);
			}else{
				//BeanToolChanJian.update(bean);
				bean.id = mBean.id;
				requestUpdate(bean);
			}
			
			showProgressDialog();
			break;

		default:
			break;
		}
	}
	
	View.OnClickListener onClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.dateEditText:
				showBirthDateDialog(mDateEdit);
				break;
			case R.id.remindEditText:
				if(TextUtils.isEmpty(mDateEdit.getText().toString())){
					UIHelper.showToast(ChanJianAddActivity.this, "请选择检查时间");
					return;
				}
				showDateTimeDialog(mRemindEdit);
				break;
			case R.id.yesText:
				mYesTextView.setSelected(true);
				mNoTextView.setSelected(false);
				
				mRemindEdit.setClickable(true);
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black));
				break;
			case R.id.noText:
				mYesTextView.setSelected(false);
				mNoTextView.setSelected(true);
				
				mRemindEdit.setClickable(false);
				mRemindEdit.setText("");
				mTime = "";
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black3));
				break;
			default:
				break;
			}
		}
	};
	
	//上传
	public void request(BeanToolChanJian bean) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("CheckDate", bean.date);
			params.put("CheckItems", bean.note);
			params.put("IsAlert", bean.remindIs);
			params.put("AlertBeforeDay", bean.remindIndex);
			params.put("AlertTime", bean.remindTime);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getUploadChanjianUrl(), map, null, this,REQUEST_DATA, true, false);
	}
	
	//更新
	public void requestUpdate(BeanToolChanJian bean) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("UPCID", bean.id);
			params.put("CheckDate", bean.date);
			params.put("CheckItems", bean.note);
			params.put("IsAlert", bean.remindIs);
			params.put("AlertBeforeDay", bean.remindIndex);
			params.put("AlertTime", bean.remindTime);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		
		ApiClient.http_post_main(Setting.getUpdateChanjianUrl(), map, null, this,REQUEST_DATA_UPDATE, true, false);
	}

	private void showBirthDateDialog(final TextView textView) {
		String babyDate = UserConfig.getConfigString(ChanJianAddActivity.this, Const.CONFIG_APP_BABY_DATE, "");
		String dateStr = "";
		if (TextUtils.isEmpty(babyDate)) {
			dateStr = DateUtilBase.stringFromDate(new Date(),DateUtilBase.YEAR_MONTH_DAY);
		} else {
			Date date = DateUtilBase.dateFromString(babyDate,DateUtilBase.YEAR_MONTH_DAY);
			dateStr = DateUtilBase.stringFromDate(date,DateUtilBase.YEAR_MONTH_DAY);
		}

		Date date = DateUtilBase.dateFromString(dateStr,DateUtilBase.YEAR_MONTH_DAY);
		MyDialog dialog = new MyDialog(ChanJianAddActivity.this)
				.setTitle("请选择检查日期")
				.setDateTimePicker(date, DateType.YEAR_MONTH_DAY)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// 如果是个数,则显示为"02"的样式
						WheelView wv_year = (WheelView) v
								.findViewById(R.id.year);
						WheelView wv_month = (WheelView) v
								.findViewById(R.id.month);
						WheelView wv_day = (WheelView) v.findViewById(R.id.day);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
								+ "-"
								+ decimal.format((wv_month.getCurrentItem() + 1))
								+ "-"
								+ decimal.format((wv_day.getCurrentItem() + 1));

//						if(DateUtil.getLongTime(text) > DateUtil.getLongTime(DateUtil.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY))){
//							UIHelper.showToast(ChanJianAddActivity.this, "不能选择未来时间");
//						}else{
							textView.setText(text);
//						}
						
					}
				});

		dialog.create(null).show();
	}
	
	@SuppressLint("InflateParams")
	private void showDateTimeDialog(final TextView textView) {
		View view = LayoutInflater.from(ChanJianAddActivity.this).inflate(R.layout.tool_yimiao_date_view, null);
		
		//------ string wheel
		final WheelView wv_content = (WheelView) view.findViewById(R.id.custom);
		wv_content.setAdapter(new ArrayWheelAdapter<String>(mDateArray));
		wv_content.setCurrentItem(1);
		
        //------ 时：分
		int hour = 0;
		int minutes = 0;

		Calendar calendar = Calendar.getInstance();

		calendar.setTime(new Date());

		hour = calendar.get(Calendar.HOUR_OF_DAY);
		minutes = calendar.get(Calendar.MINUTE);

		// 时
		final WheelView wv_hour = (WheelView) view.findViewById(R.id.hour);
		wv_hour.setAdapter(new NumericWheelAdapter(0, 23));
		wv_hour.setCyclic(true);// 可循环滚动
		wv_hour.setLabel("时");// 添加文字
		wv_hour.setCurrentItem(hour);// 初始化时显示的数据

		// 分
		final WheelView wv_minutes = (WheelView) view.findViewById(R.id.minute);
		wv_minutes.setAdapter(new NumericWheelAdapter(0, 59));
		wv_minutes.setCyclic(true);
		wv_minutes.setLabel("分");
		wv_minutes.setCurrentItem(minutes);

		// 根据屏幕密度来指定选择器字体的大小
		int textSize = UtilityBase.getTextNumberSize(ChanJianAddActivity.this);

		wv_content.TEXT_SIZE = textSize;
		wv_hour.TEXT_SIZE = textSize;
		wv_minutes.TEXT_SIZE = textSize;
		
		MyDialog dialog = new MyDialog(ChanJianAddActivity.this)
				.setTitle("请选择时间")
				.addView(view)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						mCurrentItem = wv_content.getCurrentItem();
						
						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = mDateArray[mCurrentItem]
								+" "
								+decimal.format((wv_hour.getCurrentItem() ))
								+ ":"
								+decimal.format((wv_minutes.getCurrentItem() ));

						textView.setText(text);

						mTime = decimal.format((wv_hour.getCurrentItem() ))
								+ ":"
								+decimal.format((wv_minutes.getCurrentItem() ));
					}
				});

		dialog.create(null).show();
	}

	TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			int len = s.toString().length();

			if (len <= mMaxLength) {

				mCountTextView.setTextColor(getResources().getColor(R.color.color_text_black2));
			} else {

				mCountTextView.setTextColor(getResources().getColor(R.color.color_text_highlight));
			}
			mCountTextView.setText(String.format("(%d/%d)", len, mMaxLength));
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};
	
	@Override
	public void RequestComplete(Object arg0, Object arg1) {
		ObserverManager.getInstance().notify(ObserverConst.NOTIFY_CHANJIAN_CHANGE, null,null);
		hideProgressDialog();
		finish(true);
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		ObserverManager.getInstance().notify(ObserverConst.NOTIFY_CHANJIAN_CHANGE, null,null);
		hideProgressDialog();
		finish(true);
	}
	
}
